package com.sort;

import java.util.Arrays;

/**
 * Bubble sort is a simple sorting algorithm. 
 * It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and 
 * swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, 
 * which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. 
 * Because it only uses comparisons to operate on elements, it is a comparison sort.
 * 
 * @author Shekhar
 *
 */
public class BubbleSorter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] unSortedArray = new int[]{5,1,4,2,8};
		System.out.println("UnSorted Array: "+Arrays.toString(unSortedArray));
		int[] sortedArray = sort(unSortedArray);
		System.out.println("Sorted Array: "+Arrays.toString(sortedArray));
	}
	
	public static int[] sort(int[] array){
		if(array.length<1){
			return array;
		}
		for(int i = 0;i < array.length - 2;i++){
			System.out.println("**********************Pass Started***************** "+i);
			for(int j = 1;j<array.length-i;j++){
				if(array[j-1] > array[j]){
					int temp = array[j-1];
					array[j-1] = array[j];
					array[j] = temp;
				}
				System.out.println(Arrays.toString(array));
			}
			System.out.println("**********************Pass Completed***************** "+i);
		}
		return array;
	}

}
